import axios from 'axios';

// API配置 - 负载均衡配置
const API_CONFIG = {
  // 服务实例列表
  SERVERS: ['http://localhost:8001', 'http://localhost:8002'],
  // 网关地址（备用）
  GATEWAY_URL: 'http://localhost:9527',
  // 消费者服务地址（备用）
  CONSUMER_URL: 'http://localhost:80'
};

// 客户端负载均衡实现
const LOAD_BALANCER_KEY = 'promotion_loadbalancer_counter';

// 获取请求计数器
const getRequestCount = () => {
  const stored = localStorage.getItem(LOAD_BALANCER_KEY);
  return stored ? parseInt(stored, 10) : 0;
};

// 保存计数器
const setRequestCount = (count) => {
  localStorage.setItem(LOAD_BALANCER_KEY, count.toString());
};

// 轮询选择服务器
const getNextServer = () => {
  const currentCount = getRequestCount();
  const serverIndex = currentCount % API_CONFIG.SERVERS.length;
  const server = API_CONFIG.SERVERS[serverIndex];
  const nextCount = currentCount + 1;

  setRequestCount(nextCount);

  // 简化日志输出
  console.log(`🔄 LoadBalancer: ${server}`);

  return server;
};

// 创建一个支持负载均衡的axios实例
const apiClient = axios.create({
  timeout: 10000
});

// 请求拦截器 - 负载均衡
apiClient.interceptors.request.use(
  config => {
    // 动态选择服务器
    config.baseURL = getNextServer();

    // 添加请求头标识
    config.headers['X-LoadBalancer-Client'] = 'promotion-frontend';
    config.headers['X-Target-Server'] = config.baseURL;

    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器 - 处理故障转移
apiClient.interceptors.response.use(
  response => {
    return response;
  },
  async error => {
    const originalRequest = error.config;

    // 故障转移：如果当前服务器不可用，尝试下一个
    if (error.code === 'ECONNREFUSED' && !originalRequest._retry) {
      console.warn(`❌ 服务器不可用，尝试故障转移...`);
      originalRequest._retry = true;
      originalRequest.baseURL = getNextServer();

      try {
        return await apiClient(originalRequest);
      } catch (retryError) {
        console.error('故障转移失败:', retryError.message);
      }
    }

    console.error('API请求失败:', error.message);
    return Promise.reject(error);
  }
);

// 基础的GET请求
export const get = async (url, params = {}) => {
  try {
    const response = await apiClient.get(url, { params });
    return response.data;
  } catch (error) {
    console.error('请求失败:', error);
    throw error;
  }
};

// 基础的POST请求
export const post = async (url, data) => {
  try {
    console.log('发送POST请求:', { url, data });
    const response = await apiClient.post(url, data);
    console.log('POST请求响应:', { url, status: response.status, data: response.data });
    return response.data;
  } catch (error) {
    console.error('POST请求失败:', { url, error: error.message, response: error.response });
    throw error;
  }
};

// 基础的PUT请求
export const put = async (url, data) => {
  try {
    console.log('发送PUT请求:', { url, data });
    const response = await apiClient.put(url, data);
    console.log('PUT请求响应:', { url, status: response.status, data: response.data });
    return response.data;
  } catch (error) {
    console.error('PUT请求失败:', { url, error: error.message, response: error.response });
    throw error;
  }
};

// 基础的DELETE请求
export const del = async (url) => {
  try {
    console.log('发送DELETE请求:', { url });
    const response = await apiClient.delete(url);
    console.log('DELETE请求响应:', { url, status: response.status, data: response.data });
    return response.data;
  } catch (error) {
    console.error('DELETE请求失败:', { url, error: error.message, response: error.response });
    throw error;
  }
};

// 重置负载均衡计数器（可选功能）
export const resetLoadBalancer = () => {
  setRequestCount(0);
  console.log('🔄 负载均衡计数器已重置');
};

export default {
  get,
  post,
  put,
  del,
  resetLoadBalancer,
  API_CONFIG
};